﻿using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace Edu.Web.Security
{
    public class FormAuthorizeAttribute : System.Web.Mvc.AuthorizeAttribute
    {
        public FormAuthorizeAttribute()
        {
        }

        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext.ActionDescriptor.IsDefined(typeof(AllowAnonymousAttribute), false))
            {
                return;
            }
            var principal = filterContext.HttpContext.User as FormsPrincipal<User>;
            if (principal != null)
            {
                //权限验证
                if (!principal.IsInRole(base.Roles) || !principal.IsInUser(base.Users))
                {
                    SetUnAuthorizedResult(filterContext);
                    HandleUnauthorizedRequest(filterContext);
                    return;
                }
            }

            base.OnAuthorization(filterContext);
        }

        private void SetUnAuthorizedResult(AuthorizationContext filterContext)
        {
            HttpRequestBase request = filterContext.HttpContext.Request;
            if (request.IsAjaxRequest())
            {
                //处理ajax请求
                filterContext.HttpContext.Response.StatusCode = 403;
                filterContext.Result = new ContentResult() { Content = "{\"error\"/:\"-1\"}" };
            }
            else
            {
                //跳转到登录页面
                string loginUrl = FormsAuthentication.LoginUrl + "?ReturnUrl=" + HttpUtility.UrlEncode(filterContext.HttpContext.Request.Url.ToString());
                filterContext.Result = new RedirectResult(loginUrl);
            }
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            FormsAuthentication.SignOut();
            //验证不通过,直接跳转到相应页面，注意：如果不使用以下跳转，则会继续执行Action方法
            //跳转到登录页面
            string loginUrl = FormsAuthentication.LoginUrl + "?ReturnUrl=" + HttpUtility.UrlEncode(filterContext.HttpContext.Request.Url.PathAndQuery);
            filterContext.Result = new RedirectResult(loginUrl);
        }
    }
}